package com.sunni.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class DateTypeHandler extends BaseTypeHandler<Date> { // 要转成java类属性的类型

    // java属性的类型 转成 数据库字段的类型
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setLong(i,parameter.getTime()); //i :java类的属性、parameter.getTime() :java的那个Date类型参数(birthday)转成long类型
    }

    // 数据库字段的类型 转成 java属性的类型
    @Override
    public Date getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        long birthday = resultSet.getLong(columnName); // 取出Long类型的字段(birthday)
        Date date = new Date(birthday); // birthday从库的BigInt类型 转成 java Date类型
        return date;
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        long birthday = resultSet.getLong(columnIndex);
        Date date = new Date(birthday);
        return date;
    }

    @Override
    public Date getNullableResult(CallableStatement resultSet, int columnIndex) throws SQLException {
        long birthday = resultSet.getLong(columnIndex);
        Date date = new Date(birthday);
        return date;
    }
}
